package me.shurufa.activities;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.fragments.BookShelvesFragment;
import me.shurufa.fragments.DiscoverFragment;
import me.shurufa.fragments.ProfileFragment;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.crop.util.FileUtils;


public class MainActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.tab_discover)
    TextView tabDiscover;
    @Bind(R.id.tab_bookshelves)
    TextView tabBookshelves;
    @Bind(R.id.tab_pickbook)
    TextView tabPickbook;
    @Bind(R.id.tab_profile)
    TextView tabProfile;

    public static final int CAMERA_REQUEST_CODE=3824;

    private int currentFragmentIndex;
    private SparseArray<Fragment> fragments = new SparseArray<Fragment>(3);
    private View[] tabButtons = new View[4];

    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_main;
        super.onCreate(savedInstanceState);
// 配置在线策略 检查更新//TODO 需添加key至manifest
        MobclickAgent.updateOnlineConfig(this);
        UmengUpdateAgent.update(this);
//异常退出后所有内存中的全局变量会被销毁 所以再次判断
        if (Global.currentUser==null)
            Global.appInit(this);
        uiInit();
        switchFragemnt(0,true);
    }

    private void uiInit() {
        tabDiscover.setOnClickListener(this);
        tabBookshelves.setOnClickListener(this);
        tabPickbook.setOnClickListener(this);
        tabProfile.setOnClickListener(this);
        tabButtons[0] = tabDiscover;
        tabButtons[1] = tabBookshelves;
        tabButtons[2] = tabProfile;
//        前三个为Fragment 所以2与3互换位置
        tabButtons[3] = tabPickbook;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {}

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {}


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tab_discover:
                switchFragemnt(0,false);
                break;
            case R.id.tab_bookshelves:
                switchFragemnt(1,false);
                break;
            case R.id.tab_pickbook:
                //打开自定义相机界面 要先申请权限
                Intent intent = new Intent(MainActivity.this,CameraActivity.class);
                startActivity(intent);
                break;
            case R.id.tab_profile:
                switchFragemnt(2,false);
                break;
            default:
                break;
        }

    }


    public void switchFragemnt(int id,boolean force){
        if (currentFragmentIndex == id && !force) {
            return;
        }
        tabButtons[currentFragmentIndex].setSelected(false);
        Fragment oldFragment = fragments.get(currentFragmentIndex);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (oldFragment != null)
            ft.hide(oldFragment);

        currentFragmentIndex = id;
        tabButtons[currentFragmentIndex].setSelected(true);
        Fragment newFragment = fragments.get(currentFragmentIndex);
//        TODO 设置按钮颜色
        if (newFragment == null) {
            switch (currentFragmentIndex) {
                case 0:
                    newFragment = new DiscoverFragment();
                    break;
                case 1:
                    newFragment = new BookShelvesFragment();
                    break;
                case 2:
                    newFragment = new ProfileFragment();
                    break;
            }
            fragments.put(currentFragmentIndex, newFragment);
        }
        if (newFragment != null) {
            if (!newFragment.isAdded()) {
                ft.add(R.id.fragments, newFragment, String.valueOf(currentFragmentIndex));
            }
            ft.show(newFragment);
        }
        ft.commitAllowingStateLoss();
    }


//    double click
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
            exitBy2Click();
        }
        return false;
    }

    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true;
            Toast.makeText(this, getString(R.string.double_click_back), Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);

        } else {
            finish();
        }
    }

//    Event bus

    /**
     * 相机拍照成功后 切换到书架页
     * @param intent
     */
    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (intent.getAction().equals(Constants.ACTION_MAIN_SWITCH)){
            switch (intent.getIntExtra(Constants.EXTRA_SWITCH_INDEX,0)) {
                case 0:
                    switchFragemnt(0,false);
                    break;
                case 1:
                    switchFragemnt(1,false);
                    break;
                case 2:
                    switchFragemnt(2,false);
                    break;
            }
        }else if (intent.getAction().equals(Constants.ACTION_ADD_DIGEST_COMPLETE))
            switchFragemnt(1,false);
    }


//    退出应用时 删除照相和上传头像的临时文件
    @Override
    protected void onDestroy() {
        File mTempDir = new File( Environment.getExternalStorageDirectory(),"shurufa_temp");
        if(mTempDir.exists()){
            FileUtils.deleteFile(mTempDir);
        }
        super.onDestroy();
    }
}
